/**
 *上海交大-鹏越惊虹
 */

package org.infosec.lc.exercises.threads;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**  
 * @Title: ThreadPoolExample.java
 * @Package org.infosec.lc.exercises.threads.ThreadPoolExample
 * @Description: TODO
 * @author 林超 
 * @date Apr 16, 2013 2:16:51 PM
 * @version V1.0  
 */
public class ThreadPoolExample {
	private final int nThreads;
	private final PoolWorker[] pool;
	private final LinkedList queue;
	
	public ThreadPoolExample(int nThreads){
		this.nThreads = nThreads;
		queue = new LinkedList();
		pool = new PoolWorker[nThreads];
		
		for(int i=0;i<nThreads;i++){
			pool[i] = new PoolWorker();
			pool[i].start();
		}
	}
	
	public void execute(Runnable r){
		synchronized (queue) {
			queue.addLast(r);
			queue.notify();
		}
	}
	
	private class PoolWorker extends Thread{

		@Override
		public void run() {
			Runnable r;
			
			while(true){
				synchronized (queue) {
					while(queue.isEmpty()){
						try {
							queue.wait();
							System.out.println("...........");
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					
					r = (Runnable) queue.removeFirst();
				}
				
				try {
					r.run();
				} catch (RuntimeException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	/**
	 * @Title: main
	 * @Description: TODO
	 */
	public static void main(String[] args) {
		ThreadPoolExample tp = new ThreadPoolExample(3);
		for(int i=0;i<2;i++){
			tp.execute(new Runnable() {
				
				public void run() {
					for(int j=0;j<5;j++){
						try {
							TimeUnit.SECONDS.sleep(1);
							System.out.println("!");
							System.out.println("------------------------------");
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
		}
	}

}
/**Code End*/